package cn.wangsy.zhidao.p20170111;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

public class JdbcTest {

	public static void main(String[] args) throws ClassNotFoundException, SQLException {
		
		//加载驱动
		Class.forName("com.mysql.jdbc.Driver");

		//获取数据库连接
		String user = "root" ,password = "mysql",url="jdbc:mysql://localhost:3306/test??characterEncoding=utf8";
		Connection connection = DriverManager.getConnection(url, user, password);
			
		//增加
		String sql = "insert into t1(id,name) values(?,?)";
		PreparedStatement statement = connection.prepareStatement(sql);
		statement.setString(1, "123123123");
		statement.setString(2, "jdbc");
		System.out.println(statement.executeUpdate());
		
		//查询
		sql = "select * from t1";
		Statement query = connection.createStatement();
		ResultSet rs = query.executeQuery(sql);
		while(rs.next()){
			System.out.println(rs.getString("id")+","+rs.getString("name"));
		}
		
		//修改
		sql = "update t1 set name = ? where id = ?";
		statement = connection.prepareStatement(sql);
		statement.setString(1, "java");
		statement.setString(2, "123123123");
		System.out.println(statement.executeUpdate());
		
		//删除
		sql = "delete from t1 where id = ?";
		statement = connection.prepareStatement(sql);
		statement.setString(1, "123123123");
		System.out.println(statement.executeUpdate());
		
		connection.close();
		
	}

}
